#include "libio.h" 

using namespace std;
const string& filename = "./station.json";

// 读取 JSON 文件并解析到 BusLine 结构
bool IO::readFromJsonFile2Algorithm(vector<BusLine>& busLines)
{
    ifstream file(filename);
    if (!file.is_open()) {
        cerr << "File could not be opened!" << endl;
        return false;
    }

    Json::Reader reader;
    Json::Value root;
    if (!reader.parse(file, root, false)) {
        cerr << "JSON parse failed" << endl;
        return false;
    }

    // 遍历每条公交线路
    for (const auto& lineName : root.getMemberNames()) {
        Json::Value line = root[lineName];
        BusLine busLine;
        const Json::Value& stations = line["站点表"];
        string startStation = stations[0]["站名"].asString();
        string endStation = stations[stations.size() - 1]["站名"].asString();
        
        // 设置线路名称为 "起点站-终点站"
        // busLine.lineName = lineName + "-" + endStation + "方向";
        busLine.lineName = lineName;
        busLine.firstBusTime = line["始发时间"].asString();
        busLine.lastBusTime = line["结束时间"].asString();
        
        for (unsigned int i = 0; i < stations.size(); ++i) {
            const Json::Value& station = stations[i];
            string stationName = station["站名"].asString();
            busLine.stations.push_back(stationName);
            
            // 处理站点间的时间间隔
            if (i < stations.size() - 1) {
                string nextStationName = stations[i+1]["站名"].asString();
                int travelTime = station["下一站间隔"].asInt();
                busLine.travelTimes[{stationName, nextStationName}] = travelTime;
            }
        }

        // 原始线路存入集合
        busLines.push_back(busLine);

        // 生成反向线路
        BusLine reverseLine;
        // reverseLine.lineName = lineName + "-" + startStation + "方向"; // 反向线路名称
        reverseLine.lineName = lineName; // 反向线路名称
        reverseLine.firstBusTime = busLine.firstBusTime;
        reverseLine.lastBusTime = busLine.lastBusTime;

        for (auto it = busLine.stations.rbegin(); it != busLine.stations.rend(); ++it) {
            reverseLine.stations.push_back(*it);
        }

        for (auto it = busLine.travelTimes.begin(); it != busLine.travelTimes.end(); ++it) {
            reverseLine.travelTimes[{it->first.second, it->first.first}] = it->second;
        }

        // 将反向线路加入集合
        busLines.push_back(reverseLine);
    }
    for (const auto& line : busLines) 
    {
        for (const auto& station : line.stations) 
        {
            BusSystem::routes[station].push_back(line);
        }
    }

    return true;
}

// 输出每条线路的信息
void IO::showBusLines(vector<BusLine>& busLines)
{
    for (const auto& line : busLines) {
        cout << "线路名称: " << line.lineName << endl;
        cout << "首班车时间: " << line.firstBusTime << endl;
        cout << "末班车时间: " << line.lastBusTime << endl;
        cout << "站点列表: ";
        for (const auto& station : line.stations) {
            cout << station << " ";
        }
        cout << endl;
        cout << "站间时间: " << endl;
        for (const auto& travelTime : line.travelTimes) {
            cout << travelTime.first.first << " 到 " << travelTime.first.second << 
                        " 间隔: " << travelTime.second << " 分钟" << endl;
        }
        cout << "------------------------------------" << endl;
    }
}

// 录入线路信息
// void IO::admin::write2JsonbyLine(const NewLine& newLine)
// {
//     ifstream infile(filename);
//     Json::Value root;
//     infile >> root;
//     infile.close();

//     Json::Value line;
//     line["始发时间"] = newLine.first_bus_time;
//     line["结束时间"] = newLine.last_bus_time;

//     // 添加站点信息
//     Json::Value stations(Json::arrayValue);
//     for (const auto& station : newLine.stations) {
//         Json::Value stationJson;
//         stationJson["station_name"] = station.first;
//         stationJson["interval_to_next"] = station.second;
//         stations.append(stationJson);
//     }
//     line["站点表"] = stations;

//     // 将新线路添加到根目录
//     root[newLine.line_name] = line;

//     // 写回到 JSON 文件
//     ofstream outfile(filename);
//     outfile << root;
//     outfile.close();
// }

// 录入线路信息函数
bool IO::admin::write2JsonbyLine(const NewLine& newLine) 
{
    // 读取 JSON 文件
    ifstream infile(filename);
    Json::Value root;

    // 检查文件是否正常读取
    if (infile.is_open()) 
    {
        infile >> root;
        infile.close();
    } else 
    {
        cerr << "Error opening file for reading: " << filename << endl;
        return false;
    }

    // 创建新线路的 JSON 结构
    Json::Value line;
    line["始发时间"] = newLine.first_bus_time;
    line["结束时间"] = newLine.last_bus_time;

    // 添加站点信息
    Json::Value stations(Json::arrayValue);
    for (const auto& station : newLine.stations) 
    {
        Json::Value stationJson;
        stationJson["站名"] = station.first;            // 使用与 JSON 中一致的键名
        stationJson["下一站间隔"] = station.second;
        stations.append(stationJson);
    }
    line["站点表"] = stations;

    // 将新线路添加到根目录
    root[newLine.line_name] = line;

    ofstream outfile(filename);
    if (outfile.is_open()) 
    {
        outfile << root;
        outfile.close();
    } else 
    {
        cerr << "Error opening file for writing: " << filename << endl;
    }
    return true;
}

// 录入站点信息
bool IO::admin::write2JsonbyStation(const NewStation& newStation)
{
    ifstream infile(filename);
    Json::Value root;
    infile >> root;
    infile.close();

    if (root.isMember(newStation.busline)) 
    {
        Json::Value& line = root[newStation.busline]["站点表"];

        Json::Value newStationJson;
        newStationJson["站名"] = newStation.new_station;
        newStationJson["下一站间隔"] = newStation.next_time;

        Json::Value newLine(Json::arrayValue); 

        for (int i = 0; i < line.size(); ++i) 
        {
            newLine.append(line[i]);
            if (line[i]["站名"].asString() == newStation.last_station) 
            {
                line[i]["下一站间隔"] = newStation.last_time;
                Json::Value newStationJson;
                newStationJson["站名"] = newStation.new_station;
                newStationJson["下一站间隔"] = newStation.next_time;

                newLine.append(newStationJson); 
            }
        }
        line = newLine;
    }

    // 写回到 JSON 文件
    ofstream outfile(filename);
    outfile << root;
    outfile.close();
    return true;
}

bool IO::admin::write2JsonbyLineTime(const string& lineName, const string& newStartTime, 
                                            const string& newEndTime)
{
    ifstream infile(filename);
    Json::Value root;
    infile >> root;
    infile.close();

    if (root.isMember(lineName)) 
    {
        Json::Value& line = root[lineName];
        line["始发时间"] = newStartTime;
        line["结束时间"] = newEndTime;
    }
    else
    {
        cout << "未找到该线路" << endl;
    }


    ofstream outfile(filename);
    outfile << root;
    outfile.close();
    return true;
}

// 删除线路信息
bool IO::admin::deleteFromJsonbyLine(const string& lineName)
{

    ifstream infile(filename);
    Json::Value root;
    infile >> root;
    infile.close();

    if (root.isMember(lineName)) 
    {
        root.removeMember(lineName);
    }
    else
    {
        cout << "未找到该线路" << endl;
    }


    ofstream outfile(filename);
    outfile << root;
    outfile.close();
    return true;
}

// 删除站点信息
bool IO::admin::deleteFromJsonbyStation(const string& lineName, const string& stationName)
{

    ifstream infile(filename);
    Json::Value root;
    infile >> root;
    infile.close();

    if (root.isMember(lineName)) {
        Json::Value& line = root[lineName]["站点表"];
        for (int i = 0; i < line.size(); ++i) {
            int fflag = 0;
            if (line[i]["站名"].asString() == stationName) {
                int nun1 = line[i-1]["下一站间隔"].asInt(); 
                int nun2 = line[i]["下一站间隔"].asInt();
                nun1 += nun2;
                line[i-1]["下一站间隔"] = nun1;
                if(line[i]["下一站间隔"].asInt() == -1){
                    cout << "所删除的站点为终点站，上一站修改为终点站" << endl; 
                    line[i-1]["下一站间隔"] = (int)-1;
                }
                line.removeIndex(i, nullptr);
                fflag = 1;
            }
            if(fflag == 1) break;
        }
    }

    ofstream outfile(filename);
    outfile << root;
    outfile.close();
    return true;
}

void echoLineInfo(const std::string& lineName){
    ifstream infile(filename);
    Json::Value root;
    infile >> root;
    infile.close();
    Json::Value& lineline = root[lineName];
    for (const auto& key : lineline.getMemberNames()) 
    {
        const Json::Value& value = lineline[key];
        if (value.isString()) 
        {
            std::cout << key << ": " << value.asString() << std::endl;
        } else {
            std::cout << key << ": " << value.toStyledString() << std::endl;
        }
    }

}

            

        